<template>
  <div class="add-goods-bg">
    <!-- 基础信息 -->
    <el-card class="section-card">
      <div class="section-title">基础信息</div>
      <el-form :model="baseForm" label-width="110px" class="base-form" :inline="false">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="货品名称" required>
              <el-input v-model="baseForm.goodsname" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="货品类型">
              <el-select v-model="baseForm.goodstypeid" placeholder="请选择">
                <el-option
                  v-for="item in goodstypeList"
                  :value="item.goodstypecoding"  :label="item.wGoodstypename" 
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生产日期">
             <el-date-picker
                v-model="baseForm.productionTime"
                type="date"
                placeholder="选择生产日期"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="规格型号">
              <el-input v-model="baseForm.goodsspecifications" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商">
              <el-select v-model="baseForm.vendorid" placeholder="请选择对应的供应商">
                <el-option
                  v-for="item in goodsVendorList"
                  :value="item.wVendorcoding"  :label="item.wVendorname" 
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="入库参考价(元)">
              <el-input v-model="baseForm.inventoryprice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="单位">
             <el-select v-model="baseForm.goodsUnitId" placeholder="请选择对应的单位">
                <el-option
                  v-for="item in goodsUnitList"
                  :value="item.unitscoding" :label="item.unitName" 
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="数量">
              <el-input v-model="baseForm.num" placeholder="输入货品数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="出库参考价(元)">
              <el-input v-model="baseForm.retrievalprice" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="货品状态">
              <el-radio-group v-model="baseForm.goodsstatus">
                <el-radio :value="1">未入库</el-radio>
                <el-radio :value="2">已入库</el-radio>
                <el-radio :value="3">未入库</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="条码批次">
              <el-input v-model="baseForm.goodsbarcodes"placeholder="请填入条码"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="保质期(月)">
              <el-input v-model="baseForm.shelflife" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        
       
      </el-form>
    </el-card>

    <!-- 上传图片 -->
    <el-card class="section-card">
      <div class="section-title">上传图片</div>
      <el-upload
        class="upload-demo"
        action="http://localhost:8080/api/app/goods/upload"
        list-type="picture-card"
        :file-list="imgList"
        :on-success="handleImgSuccess"
        :on-remove="handleRemoveImg"
        :on-error="handleImgError"
        :before-upload="beforeImgUpload"
        :limit="10"
        multiple
        accept="image/*"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <div class="upload-tip">支持jpg、png、gif格式,单个文件不超过5MB</div>
    </el-card>

    <!-- 上传附件 -->
    <el-card class="section-card">
      <div class="section-title">上传附件</div>
      <el-upload
        class="upload-demo"
        action="http://localhost:8080/api/app/goods/upload"  
        :file-list="fileList"
        :on-success="handleFileSuccess"
        :on-remove="handleRemoveFile"
        :on-error="handleFileError"
        :before-upload="beforeFileUpload"
        :limit="10"
        multiple
      >
        <el-button icon="el-icon-upload">上传</el-button>
      </el-upload>
      <div class="upload-tip">支持各种文档格式，单个文件不超过10MB</div>
    </el-card>
    <el-button @click="AddgoodsInfo" type="success">保存</el-button>
  </div>
  
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import service from '@/utils/request';

const route = useRoute();
const router = useRouter();

const baseForm = ref({
   "goodscoding": "",
    "goodsname": "",
    "goodsstatus": 1,
    "productionTime": "",
    "goodstypeid": "",
    "goodstyoeName": "",
    "goodsspecifications": "",
    "goodsUnitId": "",
    "goodsUnitName": "",
    "goodsbarcodes": "",
    "customerid": "",
    "customerName": "",
    "vendorid": "",
    "vendorName": "",
    "storageprice": 0,
    "retrievalprice": 0,
    "num": 0,
    "inventoryprice": 0,
    "shelflife": 0,
    "earlywarning": "",
    "createperson": "",
    "createtime": "2025-07-25T01:10:25.543Z",
    "updatetime": "2025-07-25T01:10:25.543Z",
    "goodaimages": "",
    "goodsfile": ""
});





const imgList = ref<any[]>([]);

// 图片上传前的验证
const beforeImgUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 图片上传成功处理
const handleImgSuccess = (response: any, file: any, fileList: any[]) => {
  imgList.value = fileList;
  
  // 更新图片URL列表
  updateImageUrls();
  
  ElMessage.success('图片上传成功');
};

// 图片上传失败处理
const handleImgError = (error: any, file: any, fileList: any[]) => {
  console.error('图片上传失败:', error);
  ElMessage.error('图片上传失败，请重试');
};

// 图片删除处理
const handleRemoveImg = (file: any, fileList: any[]) => {
  imgList.value = fileList;
  
  // 更新图片URL列表
  updateImageUrls();
  
  ElMessage.success('图片删除成功');
};

// 更新图片URL列表
const updateImageUrls = () => {
  const urls = imgList.value
    .map(file => {
      // 获取图片URL，优先使用response，其次使用url
      let url = null;
      if (file.response) {
        // 如果response是字符串，直接使用
        if (typeof file.response === 'string') {
          url =file.response;
        } else if (file.response.url) {
          // 如果response是对象，使用其url属性
          url = file.response.url;
        }
      } else if (file.url && !file.url.startsWith('blob:')) {
        // 使用原有的url，但过滤掉blob URL
        url = file.url;
      }
      return url;
    })
    .filter(Boolean); // 过滤掉空值
  
  // 使用逗号分隔所有图片路径
  baseForm.value.goodaimages = urls.join(',');
};

const fileList = ref<any[]>([]);

// 附件上传前的验证
const beforeFileUpload = (file: File) => {
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isLt10M) {
    ElMessage.error('文件大小不能超过 10MB!');
    return false;
  }
  return true;
};

// 附件上传成功处理
const handleFileSuccess = (response: any, file: any, fileListArr: any[]) => {
  fileList.value = fileListArr;
  
  // 更新附件URL列表
  updateFileUrls();
  
  ElMessage.success('附件上传成功');
};

// 附件上传失败处理
const handleFileError = (error: any, file: any, fileListArr: any[]) => {
  console.error('附件上传失败:', error);
  ElMessage.error('附件上传失败，请重试');
};

// 附件删除处理
const handleRemoveFile = (file: any, fileListArr: any[]) => {
  fileList.value = fileListArr;
  
  // 更新附件URL列表
  updateFileUrls();
  
  ElMessage.success('附件删除成功');
};

// 更新附件URL列表
const updateFileUrls = () => {
  const urls = fileList.value
    .map(file => {
      // 获取附件URL，优先使用response，其次使用url
      let url = null;
      if (file.response) {
        // 如果response是字符串，直接使用
        if (typeof file.response === 'string') {
          url = file.response;
        } else if (file.response.url) {
          // 如果response是对象，使用其url属性
          url = file.response.url;
        }
      } else if (file.url && !file.url.startsWith('blob:')) {
        // 使用原有的url，但过滤掉blob URL
        url = file.url;
      }
      return url;
    })
    .filter(Boolean); // 过滤掉空值
  
  // 使用逗号分隔所有附件路径
  baseForm.value.goodsfile = urls.join(',');
};

const customForm = reactive({
  f1: '',
  f2: '',
  f3: '',
  f5: ''
});

// 定义单位
interface GoodsUnit {
  unitscoding: string;
  unitName: string;
}
// 定义供应商
interface GoodsVendor {
  wVendorcoding: string;
  wVendorname: string;
}
// 定义类型
interface GoodsUnit {
  goodstypecoding: string;
  wGoodstypename: string;
}
const goodsUnitList = ref<GoodsUnit[]>([]);
const goodsVendorList = ref<GoodsVendor[]>([]);
const goodstypeList = ref<GoodsUnit[]>([]);
  const goodsId:any = route.query.id;
onMounted(async () => {
  // 加载单位、供应商、类型
  try {
    const [unitRes, vendorRes, typeRes] = await Promise.all([
      service.get('/api/app/goods/goods-unit-list'),
      service.get('/api/app/goods/w-vendors'),
      service.get('/api/app/goods/goods-type-list')
    ]);
    if (Array.isArray(unitRes.data)) goodsUnitList.value = unitRes.data;
    if (Array.isArray(vendorRes.data)) goodsVendorList.value = vendorRes.data;
    if (Array.isArray(typeRes.data)) goodstypeList.value = typeRes.data;
  } catch (e) {
    console.error('基础数据加载失败', e);
  }

  // 数据回显：如果有id参数，获取详情
  const goodsId:any = route.query.id;
  if (goodsId) {
    try {
      const res = await service.get('/api/app/goods/goods-dto?coding='+goodsId);
      if (res.data) {
        baseForm.value= res.data;
        
        // 处理图片回显
        if (res.data.goodaimages) {
          const imageUrls = res.data.goodaimages.split(',').filter(Boolean);
          imgList.value = imageUrls.map((url: string, index: number) => ({
            uid: -index - 1, // 使用负数避免与上传文件的uid冲突
            name: `图片${index + 1}`,
            url: 'http://localhost:8080'+url,
            status: 'success' // 标记为已上传成功
          }));
        }
        
        // 处理附件回显
        if (res.data.goodsfile) {
          const fileUrls = res.data.goodsfile.split(',').filter(Boolean);
          fileList.value = fileUrls.map((url: string, index: number) => ({
            uid: -index - 1, // 使用负数避免与上传文件的uid冲突
            name: `附件${index + 1}`,
            url: 'http://localhost:8080'+url,
            status: 'success' // 标记为已上传成功
          }));
        }
      }
    } catch (e) {
      ElMessage.error('获取货品详情失败');
    }
  }
});
const AddgoodsInfo=()=>{
  // 使用JSON.parse(JSON.stringify())来创建深拷贝，避免循环引用
  const submitData = JSON.parse(JSON.stringify(baseForm.value));
  if(goodsId==null){
service.post("/api/app/goods/goods", submitData)
    .then(res=>{
      ElMessage.success("保存成功");
      router.push("/Goods")
    })
    .catch(error => {
      console.error('保存失败:', error);
      ElMessage.error("保存失败");
    });
  }
  else{
    service.put("/api/app/goods/goods", submitData)
    .then(res=>{
      ElMessage.success("保存成功");
      router.push("/Goods")
    })
    .catch(error => {
      console.error('保存失败:', error);
      ElMessage.error("保存失败");
    });
  }
  
}
</script>

<style scoped>
.add-goods-bg {
  background: linear-gradient(135deg, #e3f0ff 0%, #f8fbff 100%);
  min-height: 100vh;
  padding: 32px;
}
.section-card {
  margin-bottom: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(64,158,255,0.06);
}
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 18px;
}
.base-form, .unit-form {
  margin-top: 12px;
}
.upload-demo {
  margin-top: 12px;
}
.upload-tip {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}
.file-item {
  margin: 6px 0;
  display: flex;
  align-items: center;
}
.file-item .el-link {
  margin-right: 8px;
}
</style>
